package com.rockcent.service.impl;

import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.SystemType;
import com.rockcent.mall.lib.dto.MenuTreeDTO;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.repository.AuthUserResourceRepository;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MerchantRepository;
import com.rockcent.mall.lib.repository.UserMerchantRepository;
import com.rockcent.service.BAuthUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * Created by hone on 17-4-5.
 */
@Service
public class BAuthUserServiceImpl extends BaseAuthUserServiceImpl implements BAuthUserService {

    private final Logger log = LoggerFactory.getLogger(BAuthUserServiceImpl.class);

    @Autowired
    private MerchantRepository merchantRepository;
    @Autowired
    private UserMerchantRepository userMerchantRepository;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private AuthUserResourceRepository authUserResourceRepository;

    @Override
    public UserInfoDto login(UserInfo userInfo, HttpServletRequest request) {
        return super.login(userInfo,request);
    }

    @Override
    public UserInfoDto getManager(Long userId, String domain, String userToken, Long merchantId) {
        UserInfoDto userInfoDto = null;
        if(userId==null || domain==null || userToken==null) {
            return userInfoDto;
        }
        userInfoDto = new UserInfoDto();
        Merchant merchant = merchantRepository.findOne(merchantId);
        if(merchant==null) {
            List<String> errors = new ArrayList();
            errors.add("商家不存在");
            userInfoDto.setErrorMessage(errors);
            return userInfoDto;
        }
        UserMerchant userMerchant = userMerchantRepository.findByUserIdAndMallIdAndMerchantId(userId,merchant.getMallId(),merchant.getId());
        if (userMerchant == null) {
            List<String> errors = new ArrayList();
            errors.add("用户没有B端权限");
            userInfoDto.setErrorMessage(errors);
            return userInfoDto;
        }
        if(userMerchant.getMerchantId()==null) {
            List<String> errors = new ArrayList();
            errors.add("用户数据异常");
            userInfoDto.setErrorMessage(errors);
            return userInfoDto;
        }
        if(userMerchant.getAvailable()==null || userMerchant.getAvailable() != Whether.YES) {
            List<String> errors = new ArrayList();
            errors.add("用户未启用");
            userInfoDto.setErrorMessage(errors);
            return userInfoDto;
        }

        List<MenuTreeDTO> menuTreeDTOs = null;
        String isSuper=null;
        //验证用户请求是否有权限,除了超级管理员
        if (userMerchant.getIsSuperAdmin()!=null) {
            if(userMerchant.getIsSuperAdmin() == Whether.YES) {
                menuTreeDTOs = getAllMenuTrees(SystemType.MERCHANT);
            } else {
                menuTreeDTOs = getMenuTrees(userMerchant.getUserId(), userMerchant.getMallId(), userMerchant.getMerchantId(), userToken);
            }
        }
        isSuper = userMerchant.getIsSuperAdmin()==null || userMerchant.getIsSuperAdmin() != Whether.YES?"NO":"YES";

        userInfoDto.setIsSuper(isSuper);
        userInfoDto.setResourceList(menuTreeDTOs);
        userInfoDto.setUserMerchant(userMerchant);

        Long userTokenTimer = 30 * 24 * 60 * 60L; // 30天 生命周期
        stringRedisTemplate.boundValueOps(UserInfo.REDIS_MERCHANT_LOGIN_PREFIX + userToken + "_" + domain).set(userMerchant.getMerchantId().toString());
        stringRedisTemplate.expire(UserInfo.REDIS_MERCHANT_LOGIN_PREFIX + userToken + "_" + domain, userTokenTimer, TimeUnit.SECONDS);
        return userInfoDto;
    }

    /**
     * 获取对应平台菜单列表
     * @param userId
     * @param mallId
     * @return
     */
    @Override
    public List<MenuTreeDTO> getMenuTrees(Long userId, Long mallId, Long merchantId, String userToken) {
        List<AuthUserResource> authUserResources = authUserResourceRepository.findByMallIdAndUserIdAndMerchantId(mallId, userId, merchantId);
        return getMenuTreeDTOs(authUserResources,userId, SystemType.MERCHANT,true,userToken);
    }
}
